package com.eeprint.common.exception;

import com.eeprint.common.utils.AjaxResult;
import org.apache.tomcat.util.http.ResponseUtil;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author wsen
 * @Date 2020/10/18 11:44
 * @Version 1.0
 */
@RestControllerAdvice
public class ControllerException {
    /**
     * 捕获MethoArgumentNotValidException异常（即参数错误），并将其中的错误结果返回给前端
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public AjaxResult handlerValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });

        return AjaxResult.success(errorMap);
    }
}
